package controller

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"openeuler.org/PilotGo/PilotGo-plugin-automation/internal/module/job_history/model"
	"openeuler.org/PilotGo/PilotGo-plugin-automation/internal/module/job_history/service"
	"openeuler.org/PilotGo/PilotGo-plugin-automation/pkg/response"
)

func RetryJob(c *gin.Context) {
	var retryReq model.TaskRetryRequest
	if err := c.ShouldBindJSON(&retryReq); err != nil {
		response.Fail(c, nil, fmt.Sprintf("请求参数错误: %s", err.Error()))
		return
	}

	// 调用服务层处理重试
	newJobId, err := service.RetryJob(&retryReq)
	if err != nil {
		response.Fail(c, nil, fmt.Sprintf("重试作业失败: %s", err.Error()))
		return
	}

	// 返回新任务ID、原任务ID和重试链信息，便于前端关联显示
	response.Success(c, gin.H{
		"new_job_id":    newJobId,
		"parent_job_id": retryReq.JobId,
	}, "作业重试成功")
}

// 添加获取关联任务的接口
func GetRelatedJobs(c *gin.Context) {
	jobId := c.Param("job_id")
	if jobId == "" {
		response.Fail(c, nil, "任务ID不能为空")
		return
	}

	relatedJobs, err := service.GetRelatedJobs(jobId)
	if err != nil {
		response.Fail(c, nil, fmt.Sprintf("获取关联任务失败: %s", err.Error()))
		return
	}

	response.Success(c, relatedJobs, "获取关联任务成功")
}

// 添加获取完整重试链的接口
func GetRetryChain(c *gin.Context) {
	jobId := c.Param("job_id")
	if jobId == "" {
		response.Fail(c, nil, "任务ID不能为空")
		return
	}

	retryChain, err := service.GetRetryChain(jobId)
	if err != nil {
		response.Fail(c, nil, fmt.Sprintf("获取重试链失败: %s", err.Error()))
		return
	}

	response.Success(c, retryChain, "获取重试链成功")
}
